package android.slc.toolbar.utils;

import android.view.Menu;
import android.view.MenuItem;

import androidx.core.view.ActionProvider;
import androidx.core.view.BaseActionProvider;
import androidx.core.view.MenuItemCompat;

/**
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2021/11/18 下午 2:04
 */
public class MenuUtils {
    public static void setOnMenuItemClickListener(Menu menu, MenuItem.OnMenuItemClickListener onMenuItemClickListener) {
        setOnMenuItemClickListener(menu, onMenuItemClickListener, false);
    }

    public static void setOnMenuItemClickListener(Menu menu, MenuItem.OnMenuItemClickListener onMenuItemClickListener, boolean onlySetActionProvider) {
        if (menu.size() != 0) {
            MenuItem menuItem;
            ActionProvider actionProvider;
            for (int i = 0; i < menu.size(); i++) {
                menuItem = menu.getItem(i);
                actionProvider = MenuItemCompat.getActionProvider(menuItem);
                if (actionProvider instanceof BaseActionProvider) {
                    BaseActionProvider baseActionProvider = (BaseActionProvider) actionProvider;
                    baseActionProvider.setSubMenuItem(menuItem.getSubMenu());
                    baseActionProvider.setOnMenuItemClickListener(onMenuItemClickListener);
                } else if (!onlySetActionProvider) {
                    menuItem.setOnMenuItemClickListener(onMenuItemClickListener);
                }
            }
        }
    }
}
